import json
import requests
from loguru import logger

ip = 'localhost'
port = '9000'

def ClientRecall(addr, data):
    ip = addr.get('ip', '')
    port = addr.get('port', '')
    if not ip or not port:
        return None

    url = f'http://{ip}:{port}/get_questions'  # 更改为服务器的 HTTP 路由

    try:
        headers = {'Content-Type': 'application/json'}
        data_json = json.dumps(data)
        response = requests.post(url, data=data_json, headers=headers)

        if response.status_code == 200:
            resp_data = response.json()
            logger.info('Success to call HTTP server.')
            return resp_data
        else:
            logger.error(f'Failed to call HTTP server, status code: {response.status_code}.')
            return None
    except Exception as e:
        logger.error(f'Failed to call HTTP server, cause: {e}.')
        return None

if __name__ == '__main__':
    addr = {'ip': ip, 'port': port}
    request = {
        'quantity': 4,
        'keyword': {
            'grade': "六年级",
            'subject': "数学",
            'topic': 1,
            'difficulty': "hard"
        }
    }
    res = ClientRecall(addr, request)
    print(res)
#[{'answer': '379.94', 'question_text': '正方形边长为22,则在正方形内画一个圆,圆的最大面积是( )。'},
# {'answer': '200.96', 'question_text': '长方形长为53,宽为16,则在长方形内画一个圆，圆的最大面积是( )。'},
# {'answer': '241.78', 'question_text': '长方形长为98,周长为350,则在长方形内画一个圆，圆的最大周长是( )。'},
# {'answer': '2461.76', 'question_text': '长方形长为62,宽为56,则在长方形内画一个圆，圆的最大面积是( )。'}]